package com.zscat.mallplus.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zscat.mallplus.active.service.ISysStoreService;
import com.zscat.mallplus.center.mapper.CenterTaskMapper;
import com.zscat.mallplus.cms.entity.CmsSubject;
import com.zscat.mallplus.cms.mapper.CmsSubjectMapper;
import com.zscat.mallplus.cms.service.ICmsSubjectService;
import com.zscat.mallplus.enums.AllEnum;
import com.zscat.mallplus.enums.ConstansValue;
import com.zscat.mallplus.enums.OrderStatus;
import com.zscat.mallplus.fenxiao.mapper.FenxiaoRecordsMapper;
import com.zscat.mallplus.oms.entity.*;
import com.zscat.mallplus.oms.service.*;
import com.zscat.mallplus.pms.entity.PmsComment;
import com.zscat.mallplus.pms.entity.PmsProduct;
import com.zscat.mallplus.pms.mapper.PmsProductMapper;
import com.zscat.mallplus.pms.service.IPmsCommentService;
import com.zscat.mallplus.sms.entity.*;
import com.zscat.mallplus.sms.mapper.SmsCouponHistoryMapper;
import com.zscat.mallplus.sms.mapper.SmsGroupMemberMapper;
import com.zscat.mallplus.sms.mapper.SmsGroupRecordMapper;
import com.zscat.mallplus.sms.service.*;
import com.zscat.mallplus.sys.entity.AdminDayStatics;
import com.zscat.mallplus.sys.entity.SysStore;
import com.zscat.mallplus.sys.entity.SysStoreCash;
import com.zscat.mallplus.sys.entity.SysStoreDepositLog;
import com.zscat.mallplus.sys.entity.SysStoreSettleRecords;
import com.zscat.mallplus.sys.mapper.AdminDayStaticsMapper;
import com.zscat.mallplus.sys.mapper.SysStoreCashMapper;
import com.zscat.mallplus.sys.mapper.SysStoreDepositLogMapper;
import com.zscat.mallplus.sys.mapper.SysStoreMapper;
import com.zscat.mallplus.sys.mapper.SysStoreSettleRecordsMapper;
import com.zscat.mallplus.ums.entity.UmsMember;
import com.zscat.mallplus.ums.service.IFenxiaoMemberTotalService;
import com.zscat.mallplus.ums.service.IUmsMemberService;
import com.zscat.mallplus.ums.service.impl.RedisUtil;
import com.zscat.mallplus.utils.DateUtils;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * https://github.com/shenzhuan/mallplus on 2018/8/24.
 * 订单超时取消并解锁库存的定时器
 * <p>
 * 1）0 0 2 1 * ? *   表示在每月的1日的凌晨2点调整任务
 * <p>
 * 　　（2）0 15 10 ? * MON-FRI   表示周一到周五每天上午10:15执行作业
 * <p>
 * 　　（3）0 15 10 ? 6L 2002-2006   表示2002-2006年的每个月的最后一个星期五上午10:15执行作
 * <p>
 * 　　（4）0 0 10,14,16 * * ?   每天上午10点，下午2点，4点
 * <p>
 * 　　（5）0 0/30 9-17 * * ?   朝九晚五工作时间内每半小时
 * <p>
 * 　　（6）0 0 12 ? * WED    表示每个星期三中午12点
 * <p>
 * 　　（7）0 0 12 * * ?   每天中午12点触发
 * <p>
 * 　　（8）0 15 10 ? * *    每天上午10:15触发
 * <p>
 * 　　（9）0 15 10 * * ?     每天上午10:15触发
 * <p>
 * 　　（10）0 15 10 * * ? *    每天上午10:15触发
 * <p>
 * 　　（11）0 15 10 * * ? 2005    2005年的每天上午10:15触发
 * <p>
 * 　　（12）0 * 14 * * ?     在每天下午2点到下午2:59期间的每1分钟触发
 * <p>
 * 　　（13）0 0/5 14 * * ?    在每天下午2点到下午2:55期间的每5分钟触发
 * <p>
 * 　　（14）0 0/5 14,18 * * ?     在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
 * <p>
 * 　　（15）0 0-5 14 * * ?    在每天下午2点到下午2:05期间的每1分钟触发
 * <p>
 * 　　（16）0 10,44 14 ? 3 WED    每年三月的星期三的下午2:10和2:44触发
 * <p>
 * 　　（17）0 15 10 ? * MON-FRI    周一至周五的上午10:15触发
 * <p>
 * 　　（18）0 15 10 15 * ?    每月15日上午10:15触发
 * <p>
 * 　　（19）0 15 10 L * ?    每月最后一日的上午10:15触发
 * <p>
 * 　　（20）0 15 10 ? * 6L    每月的最后一个星期五上午10:15触发
 * <p>
 * 　　（21）0 15 10 ? * 6L 2002-2005   2002年至2005年的每月的最后一个星期五上午10:15触发
 * <p>
 * 　　（22）0 15 10 ? * 6#3   每月的第三个星期五上午10:15触发
 */

/**
 * 如果要启用xxl 分布式定时任务 可以注释下面的注解
 */
@Slf4j
@Component
public class MallplusTask {
	private Logger logger = LoggerFactory.getLogger(MallplusTask.class);
	@Autowired
	private IOmsOrderService portalOrderService;
	@Resource
	private RedisUtil redisUtil;
	@Resource
	private PmsProductMapper productMapper;
	@Resource
	private ICmsSubjectService subjectService;
	@Resource
	private IOmsOrderService orderService;
	@Resource
	private IOmsOrderItemService orderItemService;
	@Resource
	private IUmsMemberService memberService;
	@Resource
	private FenxiaoRecordsMapper fenxiaoRecordsMapper;
	@Resource
	private SysStoreMapper storeMapper;
	@Resource
	private AdminDayStaticsMapper dayStaticsMapper;
	@Resource
	private SysStoreDepositLogMapper sysStoreDepositLogMapper;
	@Resource
	private ISmsHomeNewProductService homeNewProductService;
	@Resource
	private ISmsHomeRecommendProductService homeRecommendProductService;
	@Resource
	private ISmsHomeBrandService homeBrandService;
	@Resource
	private ISmsHomeRecommendSubjectService homeRecommendSubjectService;
	@Resource
	private IOmsOrderReturnApplyService orderReturnApplyService;
	@Resource
	private SmsGroupRecordMapper groupRecordMapper;
	@Resource
	private SmsGroupMemberMapper groupMemberMapper;

	@Resource
	private IFenxiaoMemberTotalService fenxiaoMemberTotalService;
	@Resource
	private ISmsGroupActivityService groupActivityService;
	@Resource
	private ISmsGroupService groupService;
	@Resource
	private SmsCouponHistoryMapper couponHistoryMapper;

	@Resource
	private SysStoreSettleRecordsMapper storeSettleRecordsMapper;
	@Resource
	private CmsSubjectMapper subjectMapper;
	@Resource
	private IOmsOrderSettingService orderSettingService;
	@Resource
	private IPmsCommentService commentService;
	@Resource
	private CenterTaskMapper centerTaskMapper;
	@Resource
	private ISysStoreService sysStoreService;
	@Resource
	private SysStoreCashMapper sysStoreCashMapper;
	@Resource
	private IOmsOrderOperateHistoryService orderOperateHistoryService;
	@Autowired
	private ISmsFlashPromotionProductRelationService flashPromotionProductRelationService;

	/**
	 * 更新用户过期的优惠券状态 半小时计算一次
	 */
//    @Scheduled(cron = "0 0/30 * ? * ?")
//    private void updateMemberCouponStatus() {
//        logger.info("更新用户过期的优惠券状态 半小时计算一次start = {}", new Date());
//        List<SmsCouponHistory> couponHistoryList = couponHistoryMapper.selectList(new QueryWrapper<SmsCouponHistory>().eq("use_status", 0).lt("end_time", new Date()));
//        for (SmsCouponHistory history : couponHistoryList) {
//            history.setUseStatus(3);
//            couponHistoryMapper.updateById(history);
//        }
//        logger.info("更新用户过期的优惠券状态 半小时计算一次end = {}", new Date());
//    }

	/**
	 * 拼团成功后 将订单状态改为发货 查询所有拼团成功且未处理的拼团记录 更新订单状态为发货 拼团记录为已处理
	 */
//    @Scheduled(cron = "0 0/10 * ? * ?")
//    private void pinTuanOrder() {
//        logger.info("拼团成功后 将订单状态改为发货start = {}", new Date());
//        List<SmsGroupRecord> list = groupRecordMapper.selectList(new QueryWrapper<SmsGroupRecord>().eq("status", 2).eq("handle_status", 1));
//        for (SmsGroupRecord groupRecord : list) {
//            List<SmsGroupMember> groupMembers = groupMemberMapper.selectList(new QueryWrapper<SmsGroupMember>().eq("group_record_id", groupRecord.getId()).eq("status", 2));
//            if (groupMembers != null && groupMembers.size() > 0) {
//                List<Long> ids = groupMembers.stream()
//                        .map(SmsGroupMember::getOrderId)
//                        .collect(Collectors.toList());
//                if (ids.size() > 0) {
//                    OmsOrder order = new OmsOrder();
//                    order.setStatus(OrderStatus.TO_DELIVER.getValue());
//                    order.setModifyTime(new Date());
//                    orderMapper.update(order, new QueryWrapper<OmsOrder>().in("status", ids));
//                    groupRecord.setHandleStatus(2);
//                    groupRecordMapper.updateById(groupRecord);
//                }
//            }
//        }
//        logger.info("拼团成功后 将订单状态改为发货end = {}", new Date());
//    }

	/**
	 * 退款
	 */
	// @Scheduled(cron = "0 0/10 * ? * ?")
//    @Scheduled(cron = "0 */1 * * * ?")
//    private void refund() {
//        logger.info("退款 10分支计算一次start = {}", new Date());
//        List<Integer> ids = Arrays.asList(1, 3);
//        List<OmsOrderReturnApply> returnApplyList = orderReturnApplyService.list(new QueryWrapper<OmsOrderReturnApply>().
//                eq("status", AllEnum.OmsOrderReturnApplyStatus.REFUNDING.code()).eq("refund_status", 0).in("type", ids));
//        for (OmsOrderReturnApply orderReturnApply : returnApplyList) {
//            portalOrderService.refund(orderReturnApply);
//        }
//        logger.info("退款 10分支计算一次end = {}", new Date());
//    }
	/**
	 * 退款
	 */
	@Scheduled(cron = "0 */5 * * * ?")
	public void refund() {
		List<Integer> ids = Arrays.asList(1, 2);
		List<OmsOrderReturnApply> returnApplyList = orderReturnApplyService.list(
				new QueryWrapper<OmsOrderReturnApply>().eq("status", AllEnum.OmsOrderReturnApplyStatus.REFUNDED.code())
						.eq("refund_status", 0).in("type", ids).groupBy("order_id"));
		for (OmsOrderReturnApply orderReturnApply : returnApplyList) {
			try {
				portalOrderService.refund(orderReturnApply);
				log.info("订单号：" + orderReturnApply.getOrderSn() + "执行退款", new Date());
			} catch (Exception e) {
				e.printStackTrace();
				log.error(e.getMessage());
			}
		}
	}

	/**
	 * 秒杀订单超时自动取消
	 *
	 * @throws Exception
	 */
	@Scheduled(cron = "*/1 * * * * ?")
	public void autoCancelFlashOrder() throws Exception {
		List<OmsOrder> orders = orderService.list(new QueryWrapper<OmsOrder>().eq("status", OrderStatus.INIT.getValue())
				.eq("source_type", 1).eq("order_type", 2));
		for (OmsOrder order : orders) {
			// 获取系统时间
			Date now = new Date();
			// 计算系统时间和订单创建时间差（秒）
			long plus = (now.getTime() - order.getCreateTime().getTime()) / 1000;
			OmsOrderSetting orderSetting = orderSettingService.getById(1);
			// 判断订单未支付时间是否超过规定时间
			if (plus >= orderSetting.getNormalOrderOvertime() * 60) {
				order.setStatus(OrderStatus.CLOSED.getValue());
				orderService.updateById(order);
				orderService.releaseStock(order);
				// 订单日志记录
				OmsOrderOperateHistory history = new OmsOrderOperateHistory();
				history.setOrderId(order.getId());
				history.setCreateTime(new Date());
				history.setOperateMan("系统");
				history.setOrderStatus(OrderStatus.INIT.getValue());
				history.setPreStatus(OrderStatus.CLOSED.getValue());
				history.setNote("自动取消订单");
				orderOperateHistoryService.save(history);
			}
		}
	}

	/**
	 * 正常订单超时自动取消
	 *
	 * @throws Exception
	 */
	@Scheduled(cron = "*/1 * * * * ?")
	public void autoCancelNormalOrder() throws Exception {
		List<OmsOrder> orders = orderService.list(new QueryWrapper<OmsOrder>().eq("status", OrderStatus.INIT.getValue())
				.eq("source_type", 1).eq("order_type", 1));
		for (OmsOrder order : orders) {
			// 获取系统时间
			Date now = new Date();
			// 计算系统时间和订单创建时间差（秒）
			long plus = (now.getTime() - order.getCreateTime().getTime()) / 1000;
			// 查询订单设置
			OmsOrderSetting orderSetting = orderSettingService.getById(1);
			// 判断订单未支付时间是否超过规定时间
			if (plus >= orderSetting.getNormalOrderOvertime() * 60) {
				order.setStatus(OrderStatus.CLOSED.getValue());
				orderService.updateById(order);
				orderService.releaseStock(order);
				// 订单日志记录
				OmsOrderOperateHistory history = new OmsOrderOperateHistory();
				history.setOrderId(order.getId());
				history.setCreateTime(new Date());
				history.setOperateMan("系统");
				history.setOrderStatus(OrderStatus.CLOSED.getValue());
				history.setPreStatus(OrderStatus.INIT.getValue());
				history.setNote("自动取消订单");
				orderOperateHistoryService.save(history);
			}
		}
	}

	/**
	 * 超时自动确认收货
	 *
	 * @throws Exception
	 */
	@Scheduled(cron = "*/1 * * * * ?")
	public void autoConfirmDelivery() throws Exception {
		List<OmsOrder> orders = orderService
				.list(new QueryWrapper<OmsOrder>().eq("status", OrderStatus.DELIVERED.getValue()).eq("source_type", 1));
		for (OmsOrder order : orders) {
			// 获取系统时间
			Date now = new Date();
			// 计算系统时间和订单创建时间差（秒）
			long plus = (now.getTime() - order.getDeliveryTime().getTime()) / 1000;
			// 查询订单设置
			OmsOrderSetting orderSetting = orderSettingService.getById(1);
			// 判断订单未支付时间是否超过规定时间
			if (plus >= orderSetting.getConfirmOvertime()  * 24 * 60 * 60) {
				order.setStatus(OrderStatus.TRADE_SUCCESS.getValue());
				order.setReceiveTime(new Date());
				orderService.updateById(order);
				// 订单日志记录
				OmsOrderOperateHistory history = new OmsOrderOperateHistory();
				history.setOrderId(order.getId());
				history.setCreateTime(new Date());
				history.setOperateMan("系统");
				history.setOrderStatus(OrderStatus.TRADE_SUCCESS.getValue());
				history.setPreStatus(OrderStatus.DELIVERED.getValue());
				history.setNote("自动确认收货");
				orderOperateHistoryService.save(history);
			}
		}
	}

	/**
	 * 超时自动好评
	 *
	 * @throws Exception
	 */
	@Scheduled(cron = "*/1 * * * * ?")
	public void autoComment() throws Exception {
		List<OmsOrder> orders = orderService.list(
				new QueryWrapper<OmsOrder>().eq("status", OrderStatus.TRADE_SUCCESS.getValue()).eq("source_type", 1).eq("is_comment", 1));
		for (OmsOrder order : orders) {
			// 获取系统时间
			Date now = new Date();
			// 计算系统时间和订单创建时间差（天）
			long plus = (now.getTime() - order.getReceiveTime().getTime()) / 1000;
			// 查询订单设置
			OmsOrderSetting orderSetting = orderSettingService.getById(1);
			// 判断订单未支付时间是否超过规定时间
			if (plus >= orderSetting.getCommentOvertime() * 24 * 60 * 60) {
				// 根据用户ID查询用户信息
				UmsMember member = memberService.getById(order.getMemberId());
				// 根据订单查询订单商品清单
				List<OmsOrderItem> orderItems = orderItemService
						.list(new QueryWrapper<OmsOrderItem>().eq("order_id", order.getId()));
				for (OmsOrderItem orderItem : orderItems) {
					PmsComment comment = new PmsComment();
					comment.setMemberId(member.getId());
					comment.setMemberIcon(member.getIcon());
					comment.setMemberNickName(member.getNickname());
					comment.setOrderId(order.getId());
					comment.setProductId(orderItem.getProductId());
					comment.setProductName(orderItem.getProductName());
					comment.setStar(5);
					comment.setContent("此用户未及时填写评价内容，系统默认好评。");
					comment.setProductAttribute(orderItem.getProductAttr());
					comment.setAnonymousStatus(0);
					comment.setCreateTime(new Date());
					comment.setShowStatus(0);
					comment.setStoreId(orderItem.getStoreId());
					commentService.save(comment);
					log.info("商品ID：" + comment.getProductId() + "会员评价超时系统自动默认好评");
					// 更新订单商品为已评价状态
					orderItem.setIsComment(1);
					orderItem.setCommentTime(new Date());
					orderItemService.updateById(orderItem);
				}

				// 更新订单为已评价状态
				order.setIsComment(2);
				order.setCommentTime(new Date());
				orderService.updateById(order);
			}
		}
	}

	/**
	 * 交易完成超时不允许售后
	 *
	 * @throws Exception
	 */
	@Scheduled(cron = "*/1 * * * * ?")
	public void autoBanAfterSale() throws Exception {
		List<OmsOrder> orders = orderService.list(
				new QueryWrapper<OmsOrder>().eq("status", OrderStatus.TRADE_SUCCESS.getValue()).eq("source_type", 1));
		for (OmsOrder order : orders) {
			// 获取系统时间
			Date now = new Date();
			// 计算系统时间和订单确认收货时间差（秒）
			long plus = (now.getTime() - order.getReceiveTime().getTime()) / 1000;
			// 查询订单设置
			OmsOrderSetting orderSetting = orderSettingService.getById(1);
			// 判断系统时间是否超过允许售后规定时间
			if (plus >= orderSetting.getFinishOvertime() * 24 * 60 * 60) {
				order.setAfterSaleStatus(0);
				orderService.updateById(order);
				log.info("订单号：" + order.getOrderSn() + "超过允许售后时间，禁止申请售后");
			}
		}
	}

	/**
	 * 清理 因为商品被删除 导致的数据关联问题
	 */
//    @Scheduled(cron = "0 0 6,15,20 * * ?")
//    private void clearGoodsRelate() {
//        logger.info("清理 因为商品被删除 导致的数据关联问题start = {}", new Date());
//        List<SmsHomeRecommendProduct> homeRecommendProductList = homeRecommendProductService.list(new QueryWrapper<SmsHomeRecommendProduct>().select("id,product_id"));
//        List<SmsHomeNewProduct> homeNewProducts = homeNewProductService.list(new QueryWrapper<SmsHomeNewProduct>().select("id,product_id"));
//        List<PmsProduct> productList = productMapper.selectList(new QueryWrapper<PmsProduct>().select("id"));
//        List<Long> ids = productList.stream().map(PmsProduct::getId).collect(Collectors.toList());
//        for (SmsHomeNewProduct product : homeNewProducts) {
//            if (!ids.contains(product.getProductId())) {
//                homeNewProductService.removeById(product.getId());
//            }
//        }
//        for (SmsHomeRecommendProduct product : homeRecommendProductList) {
//            if (!ids.contains(product.getProductId())) {
//                homeRecommendProductService.removeById(product.getId());
//            }
//        }
//        List<SmsGroupActivity> groupActivityList = groupActivityService.list(new QueryWrapper<SmsGroupActivity>().select("id,goods_ids"));
//        for (SmsGroupActivity product : groupActivityList) {
//            String[] goodsIds = product.getGoodsIds().split(",");
//            for (String id : goodsIds) {
//                if (!ids.contains(Long.parseLong(id))) {
//                    groupActivityService.removeById(product.getId());
//                    break;
//                }
//            }
//
//        }
//        List<SmsGroup> groupList = groupService.list(new QueryWrapper<SmsGroup>().select("id,goods_id"));
//        for (SmsGroup product : groupList) {
//            if (!ids.contains(product.getGoodsId())) {
//                groupService.removeById(product.getId());
//            }
//        }
//        logger.info("清理 因为商品被删除 导致的数据关联问题end = {}", new Date());
//    }

	/**
	 * cron表达式：Seconds Minutes Hours DayofMonth Month DayofWeek [Year]
	 * 每10分钟扫描一次，扫描设定超时时间之前下的订单，如果没支付则取消该订单 正常订单超时时间(分)
	 */
//    @Scheduled(cron = "0 0 2 * * ?")
//    //@Scheduled(cron = "0 0/50 * ? * ?")
//    private void cancelTimeOutOrder() {
//        logger.info("取消订单，并根据sku编号释放锁定库存start = {}", new Date());
//        CommonResult result = portalOrderService.cancelTimeOutOrder();
//        logger.info("取消订单，并根据sku编号释放锁定库存end:{}", result);
//    }

	/**
	 * 自动收货 发货后自动确认收货时间（天）
	 */
//     @Scheduled(cron = "0 0/15 * ? * ?")
//   // @Scheduled(cron = "0 */1 * * * ?")
//    private void autoDeliveryOrder() {
//        logger.info("自动收货start = {}", new Date());
//        CommonResult result = portalOrderService.autoDeliveryOrder();
//        logger.info("自动收货:{}", result);
//    }

	/**
	 * 自动完成交易时间，不能申请售后（天）
	 */
	/*
	 * @Scheduled(cron = "0 0/18 * ? * ?") private void autoSucessOrder() {
	 * CommonResult result = portalOrderService.autoSucessOrder();
	 * logger.info("取消订单，并根据sku编号释放锁定库存:{}", result); }
	 */

	/**
	 * 订单收货后自动好评时间（天）
	 */
//    @Scheduled(cron = "0 0/13 * ? * ?")
//   // @Scheduled(cron = "0 */1 * * * ?")
//    private void autoCommentOrder() {
//        logger.info("订单完成后自动好评时间（天）start = {}", new Date());
//        CommonResult result = portalOrderService.autoCommentOrder();
//        logger.info("订单完成后自动好评时间（天）end:{}", result);
//    }

	/**
	 * 佣金计算 计算前一天的订单 凌晨1点
	 */
	// @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(cron = "0 40 20 * * ?")
//    private void memberlevelCalator1() {
//        logger.info("佣金计算 计算前一天的订单 start....");
//        Long t1 = System.currentTimeMillis();
//        String yesteday = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.addDays(new Date(), -1));
//        List<OmsOrder> orders = orderMapper.listByDate(yesteday, 3);
//        // 获取订单为 待评价和已完成的
//        List<Long> ids = new ArrayList<>();
//        for (OmsOrder order : orders) {
//            if (order.getStatus() == OrderStatus.TRADE_SUCCESS.getValue()) {
//                ids.add(order.getId());
//            }
//        }
//        // 将条件合适的订单的 佣金记录更改状态
//        if (ids != null && ids.size() > 0) {
//            FenxiaoRecords records = new FenxiaoRecords();
//            records.setStatus("2");
//            fenxiaoRecordsMapper.update(records, new QueryWrapper<FenxiaoRecords>().in("order_id", ids));
//        }
//        // 分组佣金记录 更改用户的余额或积分
//        List<FenxiaoRecords> fenxiaoRecordss = fenxiaoRecordsMapper.listRecordsGroupByMemberId();
//        for (FenxiaoRecords fenxiaoRecords : fenxiaoRecordss) {
//            FenxiaoMemberTotal memberTotal = fenxiaoMemberTotalService.getById(fenxiaoRecords.getMemberId());
//
//            if (memberTotal != null) {
//                memberTotal.setCurrentAmout(fenxiaoRecords.getMoney().add(memberTotal.getCurrentAmout()));
//                memberTotal.setTotalAmount(fenxiaoRecords.getMoney().add(memberTotal.getTotalAmount()));
//                memberTotal.setUpdateTime(new Date());
//                fenxiaoMemberTotalService.updateById(memberTotal);
//               /* if (fenxiaoRecords.getType() == 1) { // 余额
//                    member.setBlance(member.getBlance().add(fenxiaoRecords.getMoney()));
//                } else {
//                    member.setIntegration(member.getIntegration() + fenxiaoRecords.getMoney().intValue());
//                }
//                IUmsMemberService.updateById(member);*/
//            } else {
//                UmsMember member = IUmsMemberService.getById(fenxiaoRecords.getMemberId());
//                memberTotal = new FenxiaoMemberTotal();
//                memberTotal.setName(member.getNickname());
//                memberTotal.setCurrentAmout(fenxiaoRecords.getMoney());
//                memberTotal.setTotalAmount(fenxiaoRecords.getMoney());
//                memberTotal.setFrezzAmount(BigDecimal.ZERO);
//                memberTotal.setId(fenxiaoRecords.getMemberId());
//                memberTotal.setUpdateTime(new Date());
//                fenxiaoMemberTotalService.save(memberTotal);
//            }
//
//        }
//        logger.info("佣金计算 计算前一天的订单end..,耗时" + (System.currentTimeMillis() - t1) / 1000 + "秒");
//    }

	/**
	 * 文章浏览量
	 */
//    @Scheduled(cron = "0 0/50 * * * ? ")//每1分钟
//    public void SyncNodesAndShips() {
//        logger.info("开始保存点赞数 、浏览数SyncNodesAndShips");
//        try {
//            //先获取这段时间的浏览数
//            Map<Object, Object> viewCountItem = redisUtil.hGetAll(Rediskey.ARTICLE_VIEWCOUNT_KEY);
//            //然后删除redis里这段时间的浏览数
//            redisUtil.delete(Rediskey.ARTICLE_VIEWCOUNT_KEY);
//            if (!viewCountItem.isEmpty()) {
//                for (Object item : viewCountItem.keySet()) {
//                    String articleKey = item.toString();//viewcount_1
//                    String[] kv = articleKey.split("_");
//                    Long articleId = Long.parseLong(kv[1]);
//                    Integer viewCount = Integer.parseInt(viewCountItem.get(articleKey).toString());
//                    CmsSubject subject = subjectService.getById(articleId);
//                    if (subject != null) {
//                        CmsSubject cms = new CmsSubject();
//                        cms.setId(articleId);
//                        cms.setReadCount(subject.getReadCount() + viewCount);
//                        logger.info("SyncNodesAndShips" + articleId + "," + viewCount);
//                        //更新到数据库
//                        subjectService.updateById(cms);
//                    }
//                }
//            }
//        } catch (Exception e) {
//            logger.error(e.getMessage());
//            e.printStackTrace();
//        }
//        logger.info("结束保存点赞数 、浏览数");
//    }

	/**
	 * 商品浏览量
	 */
//    @Scheduled(cron = "0 0/50 * * * ? ")//每1分钟
//    public void SyncGoodsView() {
//        logger.info("开始保存点赞数 、浏览数SyncGoodsView");
//        try {
//            //先获取这段时间的浏览数
//            Map<Object, Object> viewCountItem = redisUtil.hGetAll(Rediskey.GOODS_VIEWCOUNT_KEY);
//            //然后删除redis里这段时间的浏览数
//            redisUtil.delete(Rediskey.GOODS_VIEWCOUNT_KEY);
//            if (!viewCountItem.isEmpty()) {
//                for (Object item : viewCountItem.keySet()) {
//                    String articleKey = item.toString();//viewcount_1
//                    String[] kv = articleKey.split("_");
//                    Long articleId = Long.parseLong(kv[1]);
//                    Integer viewCount = Integer.parseInt(viewCountItem.get(articleKey).toString());
//                    PmsProduct subject = productMapper.selectById(articleId);
//                    if (subject != null) {
//                        PmsProduct p = new PmsProduct();
//                        p.setId(articleId);
//                        p.setHit(subject.getHit() + viewCount);
//                        logger.info("SyncGoodsView" + articleId + "," + viewCount);
//                        //更新到数据库
//                        productMapper.updateById(p);
//                    }
//                }
//            }
//        } catch (Exception e) {
//            logger.error(e.getMessage());
//            e.printStackTrace();
//        }
//        logger.info("结束保存点赞数 、浏览数");
//    }

	/**
	 * 商户数据日统计 凌晨1点 0 0 1 * * ?
	 */
	@Scheduled(cron = "0 3 3 * * ?")
//    @Scheduled(cron = "0 0/5 * ? * ?")
	public void storeDayStatics() throws InterruptedException {
		List<SysStore> storeList = storeMapper.selectList(new QueryWrapper<SysStore>().eq("status", 3));
		log.info("商户数据日统计：{}，共{}个商户需要需要同步", DateUtils.getNowDate(), storeList.size());

		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.MILLISECOND, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		String endTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, calendar.getTime());
		calendar.set(Calendar.HOUR_OF_DAY, -24);
		String startTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, calendar.getTime());

		// dayStaticsService.deleteAdminDayStaticsByDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,
		// calendar.getTime()));

		log.info("商户数据日统计：開始時間={}，結束時間{}", startTime, endTime);
		Thread.sleep(3 * 1000);
		for (SysStore store : storeList) {
			// List<UmsMember> memberList = IUmsMemberService.list(new
			// QueryWrapper<UmsMember>().eq("store_id",store.getId()));
			List<PmsProduct> productList = productMapper.selectList(new QueryWrapper<PmsProduct>()
					.eq("store_id", store.getId()).between("create_time", startTime, endTime));
			List<OmsOrder> orderList = orderService.list(new QueryWrapper<OmsOrder>().eq("store_id", store.getId())
					.between("modify_time", startTime, endTime));

			AdminDayStatics dayStatics = new AdminDayStatics();
			dayStatics.setGoodsCount(productList.size());
			// dayStatics.setMemberCount(memberList.size());

			Integer payOrderCount = 0;
			BigDecimal payAmount = BigDecimal.ZERO;
			Integer notPayOrderCount = 0;
			BigDecimal notPayAmount = BigDecimal.ZERO;
			for (OmsOrder omsOrder : orderList) {
				if (omsOrder.getPayAmount() != null) {
					if (omsOrder.getStatus() == OrderStatus.TRADE_SUCCESS.getValue()) {
						payOrderCount++;
						payAmount = payAmount.add(omsOrder.getPayAmount());
					} else if (omsOrder.getStatus() == OrderStatus.REFUND.getValue()) {
						notPayOrderCount++;
						notPayAmount = notPayAmount.add(omsOrder.getPayAmount());
					}
				}
			}
			dayStatics.setPayAmount(payAmount);
			dayStatics.setPayOrderCount(payOrderCount);
			dayStatics.setNotPayAmount(notPayAmount);
			dayStatics.setNotPayOrderCount(notPayOrderCount);
			dayStatics.setStoreId(store.getId());
			dayStatics.setStoreName(store.getName());
			dayStatics.setCreateTime(DateUtils.addDays(new Date(), -1));

			// 文章统计
			List<CmsSubject> subjectList = subjectMapper.selectList(new QueryWrapper<CmsSubject>()
					.eq("store_id", store.getId()).between("create_time", startTime, endTime));
			dayStatics.setArticleCount(subjectList.size());
			if (dayStatics.getPayOrderCount() > 0 || dayStatics.getNotPayOrderCount() > 0
					|| dayStatics.getGoodsCount() > 0 || dayStatics.getArticleCount() > 0) {
				dayStaticsMapper.insert(dayStatics);
			}
			log.info("商户数据日统计end====：{}，商户ID={},商户名称={}", DateUtils.getNowDate(), store.getId(), store.getName());
		}
		log.info("商户数据日统计end====：{}", DateUtils.getNowDate());
	}

	/**
	 * 商户统计 凌晨2点 0 0 2 * * ?
	 */
	@Scheduled(cron = "0 0 2 * * ?")
	// @Scheduled(cron = "0 0/10 * ? * ?")
	public void storeStatics() throws InterruptedException {
		List<AdminDayStatics> dayStatics = dayStaticsMapper.selectAdminDayStaticsGroupBySId();
		log.info("商户统计：{}，共{}个商户需要需要同步", DateUtils.getNowDate(), dayStatics.size());
		for (AdminDayStatics dayStatics1 : dayStatics) {
			SysStore store = new SysStore();
			store.setMemberCount(dayStatics1.getMemberCount());
			store.setId(dayStatics1.getStoreId());
			store.setGoodsCount(dayStatics1.getGoodsCount());
			store.setArticleCount(dayStatics1.getArticleCount());
			store.setOrderCount(dayStatics1.getPayOrderCount());
			store.setPayAmount(dayStatics1.getPayAmount());
			if (dayStatics1.getPayOrderCount() > 0) {
				SysStore sysStore = storeMapper.selectById(dayStatics1.getStoreId());
				if (sysStore != null) {
					SysStoreDepositLog entity = new SysStoreDepositLog();
					if (sysStore.getAmount() == null || sysStore.getAmount().compareTo(BigDecimal.ZERO) == 0) {
						entity.setBalance(dayStatics1.getPayAmount());
						store.setAmount(dayStatics1.getPayAmount());
					} else {
						entity.setBalance(sysStore.getAmount().add(dayStatics1.getPayAmount()));
						store.setAmount(sysStore.getAmount().add(dayStatics1.getPayAmount()));
					}
					entity.setCredit(dayStatics1.getPayAmount());
					entity.setStoreId(dayStatics1.getStoreId());
					entity.setCreateTime(new Date());
					entity.setUpdateTime(new Date());
					entity.setType(6);
					sysStoreDepositLogMapper.insert(entity);
				}

			}
			storeMapper.updateById(store);
		}
		log.info("商户统计end====：{}", DateUtils.getNowDate());
	}

	/**
	 * 每周一 生成上周的结算报告
	 *
	 * @throws InterruptedException
	 */
	@Scheduled(cron = "0 0 5 ? * MON")
	// @Scheduled(cron = "0 0/10 * ? * ?")
	public void genStoreSettleRecords() throws InterruptedException {

		List<AdminDayStatics> dayStaticss = dayStaticsMapper.selectLastWeekAdminDayStaticsGroupBySId();
		log.info("生成上周的结算报告 商户统计：{}，共{}个商户需要需要同步", DateUtils.getNowDate(), dayStaticss.size());
		for (AdminDayStatics dayStatics : dayStaticss) {
			SysStoreSettleRecords records = new SysStoreSettleRecords();
			records.setCreateTime(new Date());
			records.setPayAmount(dayStatics.getPayAmount());
			records.setStatus(0);
			records.setStoreId(dayStatics.getStoreId());
			records.setStoreName(dayStatics.getStoreName());
			storeSettleRecordsMapper.insert(records);
		}
	}

	/**
	 * 将拆单订单 更新为已完成 或者 部分退款
	 *
	 * @throws InterruptedException
	 */
	@Scheduled(cron = "0 */100 * * * ?")
	// @Scheduled(cron = "0 0/10 * ? * ?")
	public void parentOrderStatus() throws InterruptedException {
		List<Integer> ids = Arrays.asList(OrderStatus.TRADE_SUCCESS.getValue(), OrderStatus.PART_REFUND.getValue());

		List<OmsOrder> page = orderService.list(new QueryWrapper<OmsOrder>().notIn("status", ids).isNull("store_id")
				.select(ConstansValue.sampleOrderList));
		log.info("将拆单订单 更新为已完成 或者 部分退款：{}，共{}", DateUtils.getNowDate(), page.size());
		for (OmsOrder omsOrder : page) {
			List<OmsOrder> itemList = orderService.list(new QueryWrapper<OmsOrder>().eq("pid", omsOrder.getId()));
			Boolean flag = true;
			Boolean part_refund = false;
			for (OmsOrder order : itemList) {
				if (order.getStatus() != OrderStatus.TRADE_SUCCESS.getValue()) {
					flag = false;
				}
				if (order.getStatus() == OrderStatus.REFUND.getValue()) {
					part_refund = true;
				}
			}
			// 部分退款
			if (part_refund) {
				omsOrder.setStatus(OrderStatus.PART_REFUND.getValue());
				orderService.updateById(omsOrder);
			}
			// 完全成交
			if (flag) {
				omsOrder.setStatus(OrderStatus.TRADE_SUCCESS.getValue());
				orderService.updateById(omsOrder);
			}
		}
	}

	/**
	 * 拼团订单自动取退款（每小时第5分钟）
	 *
	 * @throws Exception
	 */
	@Scheduled(cron = "0 */1 * * * ?")
//	@Scheduled(cron = "0 5 0/1 * * ?")
	public void autoRefundGroupOrder() throws Exception {
		List<SmsGroupRecord> groupRecordList = groupRecordMapper.selectList(
				new QueryWrapper<SmsGroupRecord>().eq("handle_status", 1).eq("status", 1).lt("end_time", new Date()));
		for (SmsGroupRecord smsGroupRecord : groupRecordList) {
			List<SmsGroupMember> groupMemberList = groupMemberMapper.selectList(
					new QueryWrapper<SmsGroupMember>().eq("group_record_id", smsGroupRecord.getId()).eq("status", 2));
			for (SmsGroupMember smsGroupMember : groupMemberList) {
				portalOrderService.groupRefund(smsGroupMember.getOrderId());
				smsGroupMember.setStatus(3);// 状态 1>>初始状态 2支付成功 3退款成功
				groupMemberMapper.updateById(smsGroupMember);
			}
			smsGroupRecord.setHandleStatus(2);// 状态 1>>初始状态 2定时任务，将订单状态已更新
			smsGroupRecord.setStatus("3");// 状态 1>>初始状态 2拼团成功 3拼团失败
			groupRecordMapper.updateById(smsGroupRecord);
		}
	}

	// 月初00:00:00
	@Scheduled(cron = "0 0 0 1 * ? ")
//	@Scheduled(cron = "0 */1 * * * ?")
	private void countStoreCash() {
		List<SysStore> sysStoreList = sysStoreService.list(new QueryWrapper<SysStore>());
		for (SysStore sysStore : sysStoreList) {
			SysStoreCash sysStoreCash = new SysStoreCash();
			sysStoreCash.setCreateTime(new Date());
			sysStoreCash.setStoreId(sysStore.getId());
			sysStoreCash.setStoreName(sysStore.getName());
			sysStoreCash.setCreateBy("系统定时任务");
			sysStoreCash.setStatus(0);
			sysStoreCash.setVerifyStatus(0);
			sysStoreCash.setAmount(new BigDecimal(centerTaskMapper.countStoreCashByStoreId(sysStore.getId())));
			if (sysStoreCash.getAmount().compareTo(BigDecimal.ZERO) != 0) {
				sysStoreCashMapper.insert(sysStoreCash);
			}
		}
	}

}
